/*
 * @descripttion: user service
 * @author: cp
 * @Date: 2021-04-26 21:01:59
 */

const { User } = require('../db/model/index');
const { formatUser } = require('./_format');

/**
 * 获取用户信息(连接数据库)
 * @param {string} userName
 * @param {string} password
 */
async function getUserInfo(userName, password) {
  // 查询条件
  const whereOpt = {
    userName,
  };
  if (password) {
    // 合并对象
    Object.assign(whereOpt, { password });
  }

  // 查询
  const result = await User.findOne({
    attributes: ['id', 'userName', 'nickName', 'picture', 'city'],
    where: whereOpt,
  });

  if (result === null) {
    return result;
  }

  // 格式化
  const formatRes = formatUser(result.dataValues);

  return formatRes;
}

/**
 * 创建用户
 * @param {string} userName 用户名
 * @param {string} password 密码
 * @param {string} gender 性别
 * @param {string} nickName 昵称
 */
async function createUser({ userName, password, gender = 3, nickName }) {
  const result = await User.create({
    userName,
    password,
    gender,
    nickName: nickName ? nickName : userName,
  });
  return result.dataValues;
}

/**
 * 修改用户信息
 * @param {Object} param0 要修改的内容 newPassword, newNickName, newPicture, newCity
 * @param {Object} param1 查询条件 userName, password
 */
async function updateUser(
  { newPassword, newNickName, newPicture, newCity },
  { userName, password }
) {
  // 拼接修改内容
  const updateDate = {};
  if (newPassword) {
    updateDate.password = newPassword;
  }
  if (newNickName) {
    updateDate.nickName = newNickName;
  }
  if (newPicture) {
    updateDate.picture = newPicture;
  }
  if (newCity) {
    updateDate.city = newCity;
  }
  // 拼接查询条件
  const whereData = {
    userName,
  };
  if (password) {
    whereData.password = password;
  }
  const result = await User.update(updateDate, {
    where: whereData,
  });
  return result[0] > 0;
}

module.exports = {
  getUserInfo,
  createUser,
  updateUser,
};
